/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.meteocal.EJB.sessionBeans;

import it.polimi.meteocal.EJB.entities.Event;
import it.polimi.meteocal.EJB.entities.Invite;
import it.polimi.meteocal.EJB.entities.ModificationNotification;
import it.polimi.meteocal.EJB.entities.User;
import it.polimi.meteocal.EJB.entities.WeatherNotification;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Marianna
 */
@Stateless
public class EventManager {

    @PersistenceContext
    private EntityManager em;

    public void create(Event event, String username) {
        User u = em.find(User.class, username);
        event.setOrganizer(u);
        List<Invite> inviteList = new ArrayList<Invite>();
        List<ModificationNotification> modificationNotificationList = new ArrayList<ModificationNotification>();
        List<WeatherNotification> weatherNotificationList = new ArrayList<WeatherNotification>();
        event.setInviteList(inviteList);
        event.setModificationNotificationList(modificationNotificationList);
        event.setWeatherNotificationList(weatherNotificationList);
        event.setId(3);
        List<Event> eventList = u.getEventList();
        eventList.add(event);
        u.setEventList(eventList);
        em.persist(event);
    }

    public void delete(Event event) {
        Event e = find(event.getId());
        em.remove(e);
    }

    public Event find(int id) {
        return em.find(Event.class, id);
    }

    public String stringDate(int id) {
        Event e = find(id);
        DateFormat date = new SimpleDateFormat("E dd/MM/yyyy", Locale.ENGLISH);
        Date d = e.getDate();
        String day = date.format(d);
        return day;
    }

    public String stringBHour(int id) {
        Event e = find(id);
        Date d = e.getBeginningHour();
        String h = d.toString();
        String bh = h.substring(11, 16);
        return bh;
    }

    public String stringEHour(int id) {
        Event e = find(id);
        Date d = e.getEndingHour();
        String h = d.toString();
        String eh = h.substring(11, 16);
        return eh;
    }

    public List<String> orderedDate(String a) {

        Query q
                = em.createNativeQuery("SELECT DISTINCT date FROM Event WHERE ( (organizer='" + a + "') OR id IN (SELECT event FROM Invite WHERE guest='" + a + "') ) ORDER BY date ASC");
        List<Date> dList = q.getResultList();
        List<String> orDate = new ArrayList<String>();
        for (int i = 0; i < dList.size(); i++) {
            DateFormat date = new SimpleDateFormat("E dd/MM/yyyy", Locale.ENGLISH);
            Date d = dList.get(i);
            String day = date.format(d);
            orDate.add(day);
        }

        return orDate;
    }

    public List<Event> orderedTime(String a, String d) throws ParseException {
        String dd = d.substring(4, 14);
        System.out.println(dd);

        Query q
                = em.createNativeQuery("SELECT id FROM Event WHERE ( ( (organizer='" + a + "') OR id IN (SELECT event FROM Invite WHERE guest='" + a + "') ) AND (date = STR_TO_DATE('" + dd + "' , '%d/%m/%Y')) ) ORDER BY date ASC, beginning_hour ASC, ending_hour ASC");

        List<Long> evINd = q.getResultList();
        List<Event> eventsindate = new ArrayList<Event>();
        for (Long id : evINd) {
            Integer ad = id.intValue();
            int ID = ad.intValue();
            Event e = em.find(Event.class, ID);
            eventsindate.add(e);
        }

        return eventsindate;
    }

    public List<Event> allEvents(String a) {
        Query q
                = em.createNativeQuery("SELECT id FROM Event WHERE ( (organizer='" + a + "') OR id IN (SELECT event FROM Invite WHERE guest='" + a + "') ) ORDER BY date,beginning_hour ASC");
        List<Long> allEv = q.getResultList();
        List<Event> allEvents = new ArrayList<Event>();
        for (Long id : allEv) {
            Integer ad = id.intValue();
            int ID = ad.intValue();
            Event e = em.find(Event.class, ID);
            Date d = new Date();

            if (d.getYear() < e.getDate().getYear()) {
                allEvents.add(e);
            }

            if (d.getYear() == e.getDate().getYear()) {
                if (d.getMonth() < e.getDate().getMonth()) {
                    allEvents.add(e);
                }
            }

            if (d.getYear() == e.getDate().getYear()) {
                if (d.getMonth() == e.getDate().getMonth()) {
                    if (d.getDate() < e.getDate().getDate()) {
                        allEvents.add(e);
                    }
                }
            }

            if (d.getYear() == e.getDate().getYear()) {
                if (d.getMonth() == e.getDate().getMonth()) {
                    if (d.getDate() == e.getDate().getDate()) {
                        if (d.getHours() < e.getBeginningHour().getHours()) {
                            allEvents.add(e);
                        }
                    }
                }
            }

            if (d.getYear() == e.getDate().getYear()) {
                if (d.getMonth() == e.getDate().getMonth()) {
                    if (d.getDate() == e.getDate().getDate()) {
                        if (d.getHours() == e.getBeginningHour().getHours()) {
                            if (d.getMinutes() < e.getBeginningHour().getMinutes()) {
                                allEvents.add(e);
                            }
                        }
                    }
                }
            }
        }
        return allEvents;
    }

    public void confirmModific(Event e) {
        em.merge(e);
    }

    public int seeInvite(String a, int id) {
        Query q = em.createNativeQuery("SELECT id FROM Invite WHERE (guest = '" + a + "') AND (event = '" + id + "')");
        List<Long> allinv = q.getResultList();
        int[] iid = new int[1];
        for (Long iDd : allinv) {
            Integer ad = iDd.intValue();
            int ID = ad.intValue();
            iid[0] = ID;
        }

        return iid[0];
    }

    public void createModifNotif(Event e) {
        em.createNativeQuery("DELETE FROM weather_notification WHERE event = '"+ e.getId() + "' ").executeUpdate();
        Query q = em.createNativeQuery("SELECT guest FROM Invite WHERE event= '" + e.getId() + "' ");
        List<String> invitedU = q.getResultList();
        if (!(q.getResultList().isEmpty())) {
            for (String s : invitedU) {
                ModificationNotification mn = new ModificationNotification();
                mn.setEvent(e);
                mn.setReceiverUser(em.find(User.class, s));
                mn.setId(0);
                Date d = new Date();
                mn.setRecDate(d);
                em.persist(mn);
            }
        }
    }

    public List<Boolean> joins(User u, Event e){
        Query q =
                em.createNativeQuery("SELECT accept FROM Invite WHERE (guest = '" + u.getUsername() + "' AND event = '" + e.getId() + "' AND guest NOT IN (SELECT organizer FROM Event WHERE id = '" + e.getId() + "') ) ");
        return q.getResultList();
    }
    
    public List<String> invitedUsers(int id){
        return em.createNativeQuery("SELECT guest FROM Invite WHERE (accept = 1 AND event = '" + id + "') ").getResultList();
    }
    
    public List<Event> allUserEvents(String a){
        Query q =
                em.createNativeQuery("SELECT id FROM Event WHERE ( (organizer='" + a + "') OR id IN (SELECT event FROM Invite WHERE guest='" + a + "') )");
         List<Long> allEv = q.getResultList();
        List<Event> allEvents = new ArrayList<Event>();
        for (Long id : allEv) {
            Integer ad = id.intValue();
            int ID = ad.intValue();
            Event e = em.find(Event.class, ID);
            allEvents.add(e);
        }
            return allEvents;
    }
    
    public List<Boolean> invitePerEvent(String a, int e){
        Query q = em.createNativeQuery("SELECT accept FROM Invite WHERE guest= '" + a + "' AND event = '" + e + "' ");
        return q.getResultList();
    }    
}
